#pragma once

#include <iostream>
#include <sys/socket.h>
#include "Log.hpp"
#include <netinet/in.h>
#include <string.h>
#include <string>
#include <arpa/inet.h>
#include <functional>
#include "InetAddr.hpp" 

using namespace LogModule;

using func_t = std::function<std::string(const std::string &, InetAddr&)>;

const int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        : _sockfd(defaultfd) // 默认是没有创建的，与创建失败同理
        , _port(port)
        , _isrunning (false)
        , _func(func)
    {
    }

    void Init()
    {
        // 1. 创建套接字
        // 传入协议类型，使用报文不可靠通信，自动识别为UDP
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);

        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket creat error!";
            exit(1);
        }

        LOG(LogLevel::INFO) << "socket sucess,sockfd: " << _sockfd;

        // 2. 套接字创建出来了，将socket信息进行补充
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);      // host to server 端口号获取
        local.sin_addr.s_addr = INADDR_ANY; // 任何IP都可以访问服务端的特定端口，只要端口port一样

        // 3. 将套接字和对应的信息在内核与进程进行绑定
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {  
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }

        LOG(LogLevel::INFO) << "bind success, sockfd : " << _sockfd;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 开始接收消息
            char buffer[1024];
            struct sockaddr_in peer;      // 接收是发送消息的客户端信息
            socklen_t len = sizeof(peer); // unsigned int
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (s > 0)
            {
                // 将客户端信息提取
                InetAddr client(peer);

                buffer[s] = 0;
                std::string result = _func(buffer, client);

                // 将翻译后的内容发送给对应客户端
                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~UdpServer() {}

private:
    int _sockfd;
    uint16_t _port;

    bool _isrunning;
    func_t _func;
};